package com.example.cachedemo.config;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

@Configuration
//开启缓存
@EnableCaching
public class EhCacheConfig {
    public EhCacheConfig() {
        /*创建缓存管理器*/
        CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);
        /*创建一个名为system的缓存*/
        Cache<String, Object> systemCache = cacheManager.createCache("system",
                CacheConfigurationBuilder
                        .newCacheConfigurationBuilder(
                                String.class,//指定缓存的key类型为字符串
                                Object.class,//指定缓存的值类型为object
                                ResourcePoolsBuilder.heap(20)//使用堆内内存缓存20个对象
                        )
                        .withExpiry(
                                ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofHours(1))//设置1小时回收
                        )
        );
    }
}